package cn.pugle.base.thread.ticketlock;

import java.util.HashSet;
import java.util.Set;

/**
 * https://stackoverflow.com/a/660002/5142886 <br/>
 * 这里的wait/notifyAll被之处会唤醒所有的, 不太好.
 *
 * @author tzp
 * @since 2018/7/9
 */
public class TicketLock3 {
    private Set<Long> activeIds = new HashSet<>();

    public void getLock(Long ticketNumber) {
        synchronized (activeIds) {
            while (activeIds.contains(ticketNumber)) {
                try {
                    activeIds.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            activeIds.add(ticketNumber);
        }
    }

    public void removeLock(Long ticketNumber) {
        synchronized (activeIds) {
            activeIds.remove(ticketNumber);
            activeIds.notifyAll();
        }
    }
}
